$(function () {
  $('#link_reg').on('click', function () {
    $('.reg-box').show()
    $('.login-box').hide()
  })

  $('#link_login').on('click', function () {
    $('.login-box').show()
    $('.reg-box').hide()
  })

  const form = layui.form
  const layer = layui.layer

  form.verify({
    pwd: [/^[\S]{6,12}$/, '密码是6到12位，没有空格!!!'],
    repwd: function (value) {
      let pwd = $('#pwd').val()
      if (value !== pwd) return '两次密码不同！'
    },
  })

  $('#sub_reg').on('click', function (e) {
    e.preventDefault()
    const data = {
      username: $('#username').val(),
      password: $('#pwd').val(),
    }
    $.ajax({
      method: 'POST',
      url: '/api/reguser',
      data: data,
      success: function (res) {
        if (res.status !== 0) return layer.msg(res.message)

        layer.msg(res.message)
        $('#link_login').click()
      },
    })
  })

  $('#formLogin').on('submit', function (e) {
    e.preventDefault()
    console.log($(this).serialize())
    $.ajax({
      method: 'POST',
      url: '/api/login',
      data: $(this).serialize(),
      success: function (res) {
        console.log(res)
        if (res.status !== 0) return layer.msg(res.message)
        layer.msg(res.message)
        location.href = '/index.html'
        localStorage.setItem('token', res.token)
      },
    })
  })
})
